package com.solid.depend;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.Properties;


/**
 * <li>Description: 自定义环境变量 </li>
 */
public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {

    /**
     * <li>logger :日志 </li>
     */
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * <li>@Description: TODO</li>
     */
    private static String DEFAULT_FILE_NAME = "bootstrap%s.yml";

    /**
     * Post process environment.
     *
     * @param environment       the environment
     * @param springApplication the spring application
     */
    @Override
    public void postProcessEnvironment(
            ConfigurableEnvironment environment, SpringApplication springApplication) {

        try {
            Properties properties = new Properties();
            ClassPathResource defaultResource = new ClassPathResource(
                    String.format(DEFAULT_FILE_NAME, ""));
            properties.load(defaultResource.getInputStream());
            String[] profiles = environment.getActiveProfiles();
            for (String profile : profiles) {
                String fileName = String.format(DEFAULT_FILE_NAME, "-" + profile);
                ClassPathResource resource = new ClassPathResource(fileName);
                properties.load(resource.getInputStream());
            }
            PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(
                    "bootstrap", properties);
            environment.getPropertySources().addLast(propertiesPropertySource);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
